package cn.wh.scripting.defaults;

import cn.wh.builder.SqlSourceBuilder;
import cn.wh.mapping.BoundSql;
import cn.wh.mapping.SqlSource;
import cn.wh.scripting.xmltags.DynamicContext;
import cn.wh.scripting.xmltags.SqlNode;
import cn.wh.session.Configuration;

import java.util.HashMap;

/**
 * @Author wh
 * @Description 原始SQL源码，比 DynamicSqlSource 动态SQL处理快
 * @Date 2023/2/14 14:10
 * @Version 1.0
 **/
public class RawSqlSource implements SqlSource {

    private final SqlSource sqlSource;


    public RawSqlSource(Configuration configuration, SqlNode rootSqlNode, Class<?>parameterType){
        this(configuration, getSql(configuration, rootSqlNode), parameterType);
    }
    public RawSqlSource(Configuration configuration, String sql, Class<?> parameterType){
        SqlSourceBuilder sqlSourceParser = new SqlSourceBuilder(configuration);
        Class<?> clazz = parameterType == null ? Object.class : parameterType;
        sqlSource = sqlSourceParser.parse(sql, clazz, new HashMap<>());
    }
    @Override
    public BoundSql getBoundSql(Object parameterObject) {
        return sqlSource.getBoundSql(parameterObject);
    }

    private static String getSql(Configuration configuration,SqlNode rootSqlNode){
        DynamicContext context=new DynamicContext(configuration,null);
        rootSqlNode.apply(context);
        return context.getSql();
    }



}
